package com.zyd.controller.vehicle;

import com.alibaba.fastjson.JSON;
import com.zyd.constants.ErrorDef;
import com.zyd.context.HeaderContext;
import com.zyd.exception.BusinessException;
import com.zyd.io.model.VehicleEntity;
import com.zyd.io.page.PageBean;
import com.zyd.io.vo.page.MultiQueryPageVO;
import com.zyd.io.vo.res.ResBody;
import com.zyd.io.vo.vehicle.*;
import com.zyd.service.vehicle.VehicleService;
import com.zyd.service.log.LogService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/vehicles")
public class VehicleController {

    private static final Logger LOGGER = LoggerFactory.getLogger(VehicleController.class);


    @Autowired
    private VehicleService service;

    @Autowired
    private LogService logservice;

    @Autowired
    private ServletContext context;


    @PostMapping(value = "/addVehicle", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody addVehicle(@RequestBody VehicleEntity vehicle) {

        try {
            //记录操作日志
            logservice.addLog("","增加车辆");
            service.addVehicle(vehicle);
            return new ResBody(ErrorDef.SUCCESS, "新增车辆成功");
        } catch (BusinessException e) {
            LOGGER.error("", e);
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("", e);
            return new ResBody(ErrorDef.SYSTEM_ERROR, "新增车辆失败");
        }
    }

    @PostMapping(value = "/updateVehicle", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody updateVehicle(@RequestBody VehicleEntity vehicle) {

        try {
            //记录操作日志
            logservice.addLog("","修改车辆");
            service.updateVehicle(vehicle);
            return new ResBody(ErrorDef.SUCCESS, "修改车辆成功");
        } catch (BusinessException e) {
            LOGGER.error("", e);
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("", e);
            return new ResBody(ErrorDef.SYSTEM_ERROR, "修改车辆失败");
        }
    }

    @PostMapping(value = "/deleteVehicle", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody deleteVehicle(@RequestBody Map<String, Object> map) {
        try {
            //记录操作日志
            logservice.addLog("","删除车辆");
            service.deleteVehicle((String) map.get("id"));
            return new ResBody(ErrorDef.SUCCESS, "删除车辆成功");
        } catch (BusinessException e) {
            LOGGER.error("", e);
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("", e);
            return new ResBody(ErrorDef.SYSTEM_ERROR, "删除车辆失败");
        }
    }

    @PostMapping(value = "/vehicleList", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody findVehicleList(@RequestBody MultiQueryPageVO MultiQueryPageVO) {
        try {
            //记录操作日志
            logservice.addLog("","查询车辆列表");
            PageBean<VehicleEntity> page = service.findVehiclePage(MultiQueryPageVO);

            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "查询车辆列表成功");
            resBody.setData(page);
            /**
             * 保存查询的条件 导出使用
             */
            context.setAttribute("vehicleExcelParam"+ HeaderContext.get().get("userid"), MultiQueryPageVO);
            return resBody;
        } catch (BusinessException e) {
            LOGGER.error("", e);
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("", e);
            return new ResBody(ErrorDef.SYSTEM_ERROR, "查看车辆列表失败");
        }
    }

    @PostMapping(value = "/findVehicle", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody findVehicle(@RequestBody Map<String, Object> map) {
        try {
            //记录操作日志
            logservice.addLog("","查询车辆明细");
            VehicleEntity vehicle = service.findVehicle((String) map.get("id"));
            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "查询车辆成功");
            resBody.setData(vehicle);
            return resBody;
        } catch (BusinessException e) {
            LOGGER.error("", e);
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("", e);
            return new ResBody(ErrorDef.SYSTEM_ERROR, "查询车辆失败");
        }
    }


    @PostMapping(value = "/findVehicleTrack", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody findVehicleTack(@RequestBody VehicleTrackReqVO request) {
        try {
            //记录操作日志
            logservice.addLog("","查询轨迹");
            LOGGER.info("查询车辆轨迹接口,请求：" + JSON.toJSONString(request));
            List<VehicleTrackResVO> ret = service.findVehicleTrack(request);
            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "查询车辆轨迹成功");
            resBody.setData(ret);
            LOGGER.info("查询车辆轨迹接口结束");
            return resBody;
        } catch (BusinessException e) {
            LOGGER.error("", e);
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("", e);
            return new ResBody(ErrorDef.SYSTEM_ERROR, "查询车辆轨迹失败");
        }
    }

    @PostMapping(value = "/findVehicleRecord", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody findVehicle(@RequestBody VehicleRecordReqVO request) {
        try {
            //记录操作日志
            logservice.addLog("","查询过车记录");
            PageBean<VehicleRecordResVO> page = service.findVehicleRecord(request);
            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "查询过车记录成功");
            resBody.setData(page);
            return resBody;
        } catch (BusinessException e) {
            LOGGER.error("", e);
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("", e);
            return new ResBody(ErrorDef.SYSTEM_ERROR, "查询过车记录失败");
        }
    }

    @PostMapping(value = "/countVehicleFee", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody countVehicleFee(@RequestBody FeeReqVO request) {
        try {
            //记录操作日志
            logservice.addLog("","查询费用统计");
            PageBean<Map<String, Object>> ret = service.countFees(request);
            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "费用统计成功");
            resBody.setData(ret);
            return resBody;
        } catch (BusinessException e) {
            LOGGER.error("", e);
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("", e);
            return new ResBody(ErrorDef.SYSTEM_ERROR, "费用统计失败");
        }
    }

    @GetMapping(value = "excelExport/{userid}")
    public void downloadAllClassmate(@PathVariable String userid,HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");
        //记录操作日志
        logservice.addLog(userid,"导出车辆信息");
        String fileName = "zyd_data" + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据
        MultiQueryPageVO vehicleExcelParam = (MultiQueryPageVO) context.getAttribute("vehicleExcelParam"+userid);
        vehicleExcelParam.setPageSize(100000000);
        vehicleExcelParam.setCurrentPage(1);
        List<VehicleEntity> vehicleList= service.findVehicleList(vehicleExcelParam,userid);

        int rowNum = 1;

        String[] headers = {"车主姓名", "性别", "手机号", "防盗芯片", "车架号", "防盗号牌", "购买时间", "车辆颜色", "防盗险",
                "防盗险生效时间", "防盗险结束时间", "登记人", "身份证号", "地址", "车辆型号", "意外险", "生效时间", "到期时间", "电动机号","登记人","安装网点","车辆品牌","备案时间","车辆类型"};
        //headers表示excel表中第一行的表头

        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头

        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("white","白色");
        hashMap.put("black","黑色");
        hashMap.put("red","红色");
        hashMap.put("orange","橙色");
        hashMap.put("yellow","黄色");
        hashMap.put("blue","蓝色");
        hashMap.put("powder","粉色");
        hashMap.put("brown","棕色");
        hashMap.put("silverGray","银灰色");
        hashMap.put("silverWhite","银白色");
        hashMap.put("violet","紫色");
        hashMap.put("golden","金色");
        hashMap.put("green","绿色");
        hashMap.put("other","其他");

        HashMap<String, String> type = new HashMap<>();
        type.put("lun2", "两轮");
        type.put("lun3", "三轮");
        type.put("lun4", "四轮");
        type.put("motor", "摩托");
        type.put("other", "其他");


        //在表中存放查询到的数据放入对应的列
        for (VehicleEntity entity : vehicleList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(entity.getCarname());
            row1.createCell(1).setCellValue(entity.getSex() == 0 ? "男" : "女");
            row1.createCell(2).setCellValue(entity.getMobile());
            row1.createCell(3).setCellValue(entity.getTagcode());
            row1.createCell(4).setCellValue(entity.getTheftnum());//车架
            row1.createCell(5).setCellValue(entity.getVinno());//车牌getVinno()
            row1.createCell(6).setCellValue(entity.getBugtime());
            row1.createCell(7).setCellValue(hashMap.get(entity.getCarcolour()));
            row1.createCell(8).setCellValue(entity.getAccident());
            row1.createCell(9).setCellValue(entity.getStart_time());
            row1.createCell(10).setCellValue(entity.getEnd_time());
            row1.createCell(11).setCellValue(entity.getCreateid());
            row1.createCell(12).setCellValue(entity.getCarid());
            row1.createCell(13).setCellValue(entity.getCaraddress());
            row1.createCell(14).setCellValue(hashMap.get(entity.getVehiclebrand()));
            row1.createCell(15).setCellValue(entity.getAccident());
            row1.createCell(16).setCellValue(entity.getStart_time());
            row1.createCell(17).setCellValue(entity.getEnd_time());
            row1.createCell(18).setCellValue(entity.getStartmachine());
            row1.createCell(19).setCellValue(entity.getReger());
            row1.createCell(20).setCellValue(entity.getSalesite());
            row1.createCell(21).setCellValue(entity.getVehiclebrand());
            row1.createCell(22).setCellValue(entity.getKeeptime());
            row1.createCell(23).setCellValue(type.get(entity.getLighttypes()));

            rowNum++;
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
    // 车辆登记查询
    @PostMapping(value = "/findRegisterVehiclePage", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody blackCarFindList(@RequestBody MultiQueryPageVO blackcarRequestDTO) {
        try {
            PageBean<Map<String, Object>> blackPage = service.findRegisterVehiclePage(blackcarRequestDTO);

            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "查询登记成功");
            resBody.setData(blackPage);
            return resBody;
        } catch (BusinessException e) {
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return new ResBody(ErrorDef.SYSTEM_ERROR, "查看登记失败");
        }
    }
    @PostMapping(value = "/findVehicleByReger", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody findVehicleByReger(@RequestBody Map<String,String> map) {
        try {
            List<VehicleEntity> vehicleList= service.findVehicleByReger(map.get("reger"));

            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "根据reger查询车辆成功");
            resBody.setData(vehicleList);
            return resBody;
        } catch (BusinessException e) {
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return new ResBody(ErrorDef.SYSTEM_ERROR, "根据reger查询车辆失败");
        }
    }
    //    导出模板
    @GetMapping(value = "/templateDownload/{userid}")
    public void templateDownload(@PathVariable String userid,HttpServletResponse response) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");
        String fileName = "zyd_data" + ".xls";//设置要导出的文件的名字

        //新增数据行，并且设置单元格数据
        int rowNum = 1;

        String[] headers = {"车主姓名","身份证号" ,"性别", "手机号", "联系地址", "车牌号", "车架号", "防盗芯片","电动机号","来历承诺书","车辆类型","车辆品牌","区县/辖区",
                "车身颜色","购买价格","购买时间","新旧程度","套餐项","套餐开始时间","套餐结束时间","防盗险","意外险", "意外险","登记人","职业",
                "备用电话","备案时间","安装网点"};
        //headers表示excel表中第一行的表头

        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头

        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            workbook.write(response.getOutputStream());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //导入数据
    @PostMapping(value = "/excelImport")
    public ResBody excelImport(@RequestParam("workbook") MultipartFile file, HttpServletRequest request)  {
        //根据上传流信息创建工作簿
        try {
            Workbook workbook = null;
            workbook = WorkbookFactory.create(file.getInputStream());
            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "导入成功");
            service.importData(workbook);
            return resBody;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResBody(ErrorDef.SYSTEM_ERROR, "导入失败");
    }
    @PostMapping(value = "/findApplet", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody appletFindList(@RequestBody MultiQueryPageVO blackcarRequestDTO) {
        try {
            PageBean<Map<String, Object>> blackPage = service.appletFindPage(blackcarRequestDTO);

            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "查询锁车列表成功");
            resBody.setData(blackPage);
            return resBody;
        } catch (BusinessException e) {
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return new ResBody(ErrorDef.SYSTEM_ERROR, "查询锁车列表失败");
        }
    }

    /**
     * 查看审核车辆列表
     * @param multiQueryPageVO
     * @return
     */
    @PostMapping(value = "/examineVehicleList", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody examineVehicleList(@RequestBody MultiQueryPageVO multiQueryPageVO) {
        try {
            PageBean page = service.examineVehicleList(multiQueryPageVO);
            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "查询审核车辆列表成功");
            resBody.setData(page);
            return resBody;
        } catch (BusinessException e) {
            LOGGER.error("", e);
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("", e);
            return new ResBody(ErrorDef.SYSTEM_ERROR, "查询审核车辆列表成功");
        }
    }

    /**
     * 修改车辆通过审核
     * @param map
     * @return
     */
    @PostMapping(value = "/updateExamineVehicle", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody updateExamineVehicle(@RequestBody Map map) {
        try {
            String id = (String) map.get("id");
            Integer state = 1;
            service.updateExamineVehicle(id,state);

            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "通过审核成功");
            return resBody;
        } catch (BusinessException e) {
            LOGGER.error("", e);
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("", e);
            return new ResBody(ErrorDef.SYSTEM_ERROR, "通过审核失败");
        }
    }

    /**
     * 修改车辆通过审核
     * @param map
     * @return
     */
    @PostMapping(value = "/deleteExamine", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody deleteExamine(@RequestBody Map map) {
        try {
            String id = (String) map.get("id");
            service.deleteExamine(id);

            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "通过审核成功");
            return resBody;
        } catch (BusinessException e) {
            LOGGER.error("", e);
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("", e);
            return new ResBody(ErrorDef.SYSTEM_ERROR, "通过审核失败");
        }
    }
}
